import {
  setStorage, //存值
  getStorage, // 取值
  sleep
} from "./lib.js";
import axios from 'axios';
const API_BASE_URL = 'https://api.aidso.com'

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'setToken') {
      console.log('Setting token:', request.token);
      setStorage({
          dso114Token: request.token
      });
      sendResponse({ success: true });
  } else if (request.action === 'removeDso114Token') {
      try {
          console.log('[Background] Removing DSO114 token...');
          removeDso114Token();
          sendResponse({ success: true });
      } catch (error) {
          console.error('[Background] Error removing token:', error);
          sendResponse({ success: false, error: error.message });
      }
  } else if (request.type === 'getToken') {
    // 使用 chrome.storage.local 替代 localStorage
    chrome.storage.local.get(['token'], (result) => {
      sendResponse({ token: result.token });
    });
    return true; // 保持消息通道开启
  } else if (request.action === 'authorizationClicked') {
    setStorage({
      douYin_cookies: request.data.cookies
    });
    setStorage({
      douYin_localStorage: JSON.stringify(request.data.localStorage)
    });
    authorizationClickedFun(request.data)
    sendResponse({ success: true });
  }
  return true; // 保持消息通道开放
});
// API请求
chrome.webRequest.onBeforeRequest.addListener(
  async function (details) {
    // 处理请求
    // console.log('Request URL:', details.url);
    try {
      if (details.url.includes("api/media/user/info/")) {
        const isFrom = getUrlParam(details.url, "isFrom");
        // console.log('-----isFrom-----', isFrom);
        if (!isFrom) {
          // 使用 fetch 发起请求
          const response = await fetch(`${details.url}?isFrom=extension`);
          const data = await response.json();
          const { user } = data;
          const tempObj = {
            unique_id: user.short_id,
            tiktok_user_id: user.uid,
            avatar: user.avatar_medium.url_list[0] || user.avatar_larger.url_list[0] || user.avatar_thumb.url_list[0],
            nickname: user.nickname
          };
          // console.log('tempObj', tempObj);
          // 将数据存储到 页面缓存中
          await setStorage(tempObj);
          // postJs(tempObj)
        }
      }
    } catch (error) {
      console.error('Request processing error:', error);
    }
  },
  {
    urls: ["*://creator.douyin.com/*"]
  }
);
// 向js发送消息
function postJs (result) {
  // console.log('----Sending data:-------', result); // 添加调试信息
  
  // 获取当前活动标签页
  // 存储到sessionStorage
  // sessionStorage.setItem('douyin_data_info', JSON.stringify(result));
  // chrome.storage.local.set({ 'douyin_data_info': JSON.stringify(result) }, function() {
  //   console.log('User Status has been stored');
  // });
  // chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  //   if (tabs[0]) {
  //     // 向内容脚本发送消息
  //     chrome.tabs.sendMessage(tabs[0].id, { type: 'postJs', message: result }, (response) => {
  //       console.log('消息发送成功:', response);
  //     });
  //   }
  // });
}

// 更新网络请求监听器
chrome.webRequest.onBeforeSendHeaders.addListener(
  function(details) {
    if (details.url.includes("api/media/user/info/")) {
      const cookies = details.requestHeaders.find(header => header.name.toLowerCase() === 'cookie');
      if (cookies && cookies.value) {
        chrome.storage.local.set({ ApiCookie: cookies.value });
      }
    }
    return { requestHeaders: details.requestHeaders };
  },
  {
    urls: ["*://creator.douyin.com/*"]
  },
  ["requestHeaders", "extraHeaders"]
);

// 添加删除 dso114 token 的函数
function removeDso114Token() {
  setStorage({
    dso114Token: ''
  });
}

async function authorizationClickedFun(){
  // console.log('授权按钮被点击');
  const getSrc = await getStorage();
  // console.log('getSrc', getSrc);
  if (getSrc.unique_id) {
    await POSTData();
  } else {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      if (tabs.length > 0) {
        chrome.tabs.sendMessage(tabs[0].id, {
          action: 'hideLoading',
          message: '授权失效，请刷新页面后重新授权'
        });
      }
    });
  }

}

// 请求后台接口
async function POSTData() {
  const getSrc = await getStorage();
  let storageData ={
    localStorage: JSON.parse(getSrc.douYin_localStorage),
    cookies: getSrc.douYin_cookies
  }
  // console.log('storageData', storageData);
  if(!await checkPluginVersion()){
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      if (tabs.length > 0) {
        chrome.tabs.sendMessage(tabs[0].id, {
          action: 'hideLoading',
          message: '插件版本已更新，请在"AIDSO"中重新下载安装'
        });
      }
    });
    // console.log('插件版本已更新，请在"AIDSO"中重新下载安装');
    return
  }
 
  if( !storageData ||  !storageData.localStorage || !storageData.cookies){
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      if (tabs.length > 0) {
        chrome.tabs.sendMessage(tabs[0].id, {
          action: 'hideLoading',
          message: '数据抓取失败，请重新登录"创作者中心"'
        });
      }
    });
    // console.log('数据抓取失败，请重新登录"创作者中心"');
    return
  }

  // 延迟500毫秒后执行后续代码
  await sleep(500);
 
  let cookie = cookieToJson(getSrc.ApiCookie);
  let from = {
    cookie: getSrc.ApiCookie,
    setting:'',
    nick_name: getSrc.nickname,
    unique_id:getSrc.unique_id,
    tiktok_user_id:getSrc.tiktok_user_id,
    avatar:getSrc.avatar,
    session_id: cookie.sessionid
  }
  let setting = {
    uid: getSrc.tiktok_user_id,
    unique_id: getSrc.unique_id,
    uniqueId: getSrc.unique_id,
    nickname:getSrc.nickname,
    localStorage:storageData.localStorage
  };
  from.setting = JSON.stringify(setting)


  
  const dso114Token = getSrc.dso114Token;
  // console.log('dso114Token', dso114Token);
  // console.log('from', JSON.parse(JSON.stringify(from)));
  if(!dso114Token){
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      if (tabs.length > 0) {
        chrome.tabs.sendMessage(tabs[0].id, {
          action: 'hideLoading',
          message: '未登录AIDSO，请登录后刷新当前页面重新授权'
        });
      }
    });
    return
  }

  if(!dso114Token || !from.cookie || !from.setting){
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      if (tabs.length > 0) {
        chrome.tabs.sendMessage(tabs[0].id, {
          action: 'hideLoading',
          message: '数据抓取失败，请刷新当前页面重新授权'
        });
      }
    });
    return
  }
  //console.log('获取当前活动标签页');
  // 获取当前活动标签页
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    if (tabs.length > 0) {
      chrome.tabs.sendMessage(tabs[0].id, {
        action: 'showLoading',
        message: '正在同步信息...,请勿关闭页面'
      }, function(response) {
        if (chrome.runtime.lastError) {
          console.error('消息发送失败:', chrome.runtime.lastError);
        }
      });
    }
  });

  const res = await axios.post(`${API_BASE_URL}/open/api/oauth/commit/auth`, from, {
    headers:{
      'Authorization': JSON.parse(dso114Token)
    }
  });
  //console.log(res);
  setTimeout(() => {
    // 显示成功提示
  //console.log('显示成功提示');

    if(res.data.code == 200){
      
      chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        if (tabs && tabs.length > 0) {
          chrome.tabs.sendMessage(tabs[0].id, {
            action: 'hideLoading',
            message: '授权成功'
          });
        } else {
          console.error('没有找到活动标签页');
        }
      });
    }else if(res.data.code == 403){
      // 使用 chrome.tabs.query 来获取当前标签页
      chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        if (tabs && tabs.length > 0) {
          chrome.tabs.sendMessage(tabs[0].id, {
            action: 'hideLoading',
            message: '请登录"授权失效"账号'
          }, function(response) {
            if (chrome.runtime.lastError) {
              console.error('发送消息失败:', chrome.runtime.lastError);
            }
          });
        } else {
          console.error('没有找到活动标签页');
        }
      });
    }else{
        // 使用 chrome.tabs.query 来获取当前标签页
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
          if (tabs && tabs.length > 0) {
            chrome.tabs.sendMessage(tabs[0].id, {
              action: 'hideLoading',
              message: res.data.msg
            }, function(response) {
              if (chrome.runtime.lastError) {
                console.error('发送消息失败:', chrome.runtime.lastError);
              }
            });
          } else {
            console.error('没有找到活动标签页');
          }
        });
    }
  }, 200);
}

// 插件版本检测
async function checkPluginVersion(){
  return new Promise(async (resolve, reject) => {
     const response = await fetch('https://static2.douchacha.com/dso/chrome_douyin/douyin.json');
     const data = await response.json();
     if(compareVersions(chrome.runtime.getManifest().version, data.version) < 0){
       resolve(false)
     }
     resolve(true)
   })
 }
 
 function compareVersions(version1, version2) {
   // 将版本号分割成数组
   const v1 = version1.split('.').map(Number); 
   const v2 = version2.split('.').map(Number);
   
   // 找到最大长度
   const length = Math.max(v1.length, v2.length);
   
   // 对齐版本号长度，缺少的部分补0
   for (let i = 0; i < length; i++) {
       if (v1[i] === undefined) v1[i] = 0;
       if (v2[i] === undefined) v2[i] = 0;
   }
 
   // 逐个比较每个部分
   for (let i = 0; i < length; i++) {
       if (v1[i] > v2[i]) {
           return 1;  // version1 更大
       }
       if (v1[i] < v2[i]) {
           return -1; // version2 更大
       }
   }
   
   return 0;  // 两个版本相等
 }

 // URL参数解析函数
function getUrlParam(urlString, key) {
  try {
    const url = new URL(urlString);
    return url.searchParams.get(key) || "";
  } catch (error) {
    // console.error('URL parsing error:', error);
    return "";
  }
}
function cookieToJson(cookieStr) {
  const cookies = cookieStr.split(';').map(cookie => cookie.trim());
  const cookieJson = {};

  cookies.forEach(cookie => {
      const [key, value] = cookie.split('=');
      if (key && value) {
          cookieJson[key] = value;
      }
  });

  return cookieJson;
}